using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

namespace BlazorWasm
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddOidcAuthentication(options =>
            {
                builder.Configuration.Bind("Local", options.ProviderOptions);
                options.UserOptions.RoleClaim = "role";

            }).AddAccountClaimsPrincipalFactory<CustomUserFactory>();

            builder.Services.AddAuthorizationCore(option =>
            {
                string[] permissions = new string[]
                {
                    "create",
                    "retrieve",
                    "update",
                    "delete"
                };
                foreach (var p in permissions)
                {
                    option.AddPolicy(p, policy =>
                    {
                        policy.RequireClaim("permission", new string[] { p });
                    });
                }
            });

            builder.Services.AddScoped<CustomAuthorizationMessageHandler>();
            builder.Services.AddHttpClient("ServerAPI",
                    client => client.BaseAddress = new Uri("https://localhost:5002"))
                .AddHttpMessageHandler<CustomAuthorizationMessageHandler>();
            builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
                .CreateClient("ServerAPI"));

            await builder.Build().RunAsync();
        }
    }
}
